package com.youfang.sixthmedia;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.gzit.common.async.AsynCallback;
import com.gzit.store.StoreManager;
import com.gzit.utils.AndroidUtils;
import com.gzit.utils.LoadingDelegater;
import com.gzit.utils.StringUtils;
import com.youfang.sixthmedia.chat.service.BuddyMessageService;
import com.youfang.sixthmedia.common.YouFangUtils;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.controller.HeaderController;
import com.youfang.sixthmedia.message.LoginRequest;
import com.youfang.sixthmedia.message.LoginResponse;
import com.youfang.sixthmedia.message.chat.SendMessageRequest;
import com.youfang.sixthmedia.message.chat.SendMessageResponse;
import com.youfang.sixthmedia.message.model.Buddy;
import com.youfang.sixthmedia.message.model.ChatItem;
import com.youfang.sixthmedia.message.model.User;
import com.youfang.sixthmedia.net.Net;
import com.youfang.sixthmedia.net.Response;

public class ChatActivity extends Activity {

	EditText content;
	Button sendBtn;

	private Buddy buddy;

	private LinearLayout chatPanel;
	private ScrollView scrollview;
	private LoadingDelegater loading = new LoadingDelegater();

	private void setupTestStub() {
		buddy = new Buddy();
		buddy.userid = 552;
		buddy.username = "zhansheng";
		buddy.nickname = buddy.username;

		this.content.setText("hello" + System.currentTimeMillis());
		LoginRequest login = new LoginRequest();
		login.setUsername("teddy");
		login.setPassword("443260");
		Net.doHttpRemote(this, login, new LoginResponse(),
				new AsynCallback<Response>() {

					@Override
					public void callback(Response r) {
						if (!r.isOk()) {
							AndroidUtils.toastShort("登录失败");
							return;
						}

						// 登录成功...
						LoginResponse resp = (LoginResponse) r;
						User user = resp.getUser();

						// save user infomation
						user.password = "443260";
						YoufangContext.saveUserAndStartMessageService(user);

						loadHistoryMsgsAndStartMessageServices();

					}
				});
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.chat_activity);

		loading.init(this);

		content = (EditText) this.findViewById(R.id.content);
		sendBtn = (Button) this.findViewById(R.id.send);
		chatPanel = (LinearLayout) this.findViewById(R.id.chat_panel);
		scrollview = (ScrollView) this.findViewById(R.id.scrollview);
		scrollview.setSmoothScrollingEnabled(false);

		Intent intent = this.getIntent();
		buddy = (Buddy) intent.getSerializableExtra("data");

		// test...
		// setupTestStub();

		((TextView) this.findViewById(R.id.title)).setText(buddy.nickname);

		sendBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				remoteSend();
			}
		});

		loadHistoryMsgsAndStartMessageServices();

	}

	private void loadHistoryMsgsAndStartMessageServices() {
		// get message from local store related to currrent buddy

		new AsyncTask<String, Integer, List<ChatItem>>() {

			@Override
			protected List<ChatItem> doInBackground(String... params) {

				List<ChatItem> historyItems;
				try {
					historyItems = StoreManager.findByConditions(ChatItem.DUMY,
							"userid=? AND fromid=?", new String[] {
									YoufangContext.getUser().userid + "",
									buddy.userid + "" },
							" time desc  LIMIT 0,30 ");

					Collections.sort(historyItems);
					return historyItems;
				} catch (Exception e) {
					e.printStackTrace();

				}
				return null;

			}

			protected void onPreExecute() {

				loading.show("正在加载聊天数据...");

			};

			@Override
			protected void onPostExecute(List<ChatItem> historyItems) {
				super.onPostExecute(historyItems);
				loading.hide();
				if (historyItems == null) {
					return;
				}
				for (ChatItem item : historyItems) {
					if (item.mymsg == ChatItem.MY_MSG) {
						addMyMessageItem(item.content, item.time);
					} else {
						addTimeLineSaperate(item.time);
						addBuddyMessageItem(item);

					}

				}

				// scroll to bottom of scrollview
				scrollToBottom();

				// start service
				IntentFilter filter = new IntentFilter();
				filter.addAction(YoufangContext.CHAT_ATION);
				registerReceiver(messageReceiver, filter);
				BuddyMessageService.reg(ChatActivity.this, buddy);

			}
		}.execute("");

	}

	private void scrollToBottom() {
		this.scrollview.post(new Runnable() {

			@Override
			public void run() {
				scrollview.fullScroll(ScrollView.FOCUS_DOWN);
			}
		});
	}

	private void addTimeLineSaperate(long time) {
		int padding = AndroidUtils.Screen.dp2pix(5f);
		TextView timeline = new TextView(this);
		timeline.setText(YouFangUtils.getDateTimeDesc(new Date(time)));
		timeline.setGravity(Gravity.CENTER);
		timeline.setTextColor(Color.parseColor("#CCCCCC"));

		ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
				RelativeLayout.LayoutParams.FILL_PARENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);

		timeline.setPadding(0, padding, 0, padding);

		chatPanel.addView(timeline, params);

	}

	private static int myid = 1;

	private static synchronized int genID() {
		return myid++;
	}

	private void addMyMessageItem(String content, long time) {

		addTimeLineSaperate(time);

		int viewid = genID();
		RelativeLayout layout = new RelativeLayout(this);
		int padding = AndroidUtils.Screen.dp2pix(10f);
		layout.setPadding(padding, padding, padding, padding);

		ImageView headerView = new ImageView(this);
		headerView.setId(viewid);

		// get the user logo,if missed,used the default one...
		Uri uri = HeaderController.Cache
				.getFromCache(YoufangContext.getUser().userid);
		if (uri != null) {
			headerView.setImageURI(uri);
		}

		headerView.setBackgroundResource(R.drawable.chat_header);

		// add header photo
		int headerWidth = AndroidUtils.Screen.dp2pix(72f);
		RelativeLayout.LayoutParams headerParams = new RelativeLayout.LayoutParams(
				headerWidth, headerWidth);
		headerParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		layout.addView(headerView, headerParams);

		// add message item
		TextView msgView = new TextView(this);
		msgView.setGravity(Gravity.CENTER);
		msgView.setTextColor(Color.BLACK);
		msgView.setBackgroundResource(R.drawable.chat_my_bg);
		RelativeLayout.LayoutParams messageParams = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		messageParams.addRule(RelativeLayout.LEFT_OF, viewid);
		messageParams.setMargins(0, 0, padding, 0);

		layout.addView(msgView, messageParams);
		msgView.setText(content);

		chatPanel.addView(layout, new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.FILL_PARENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT));

		// scroll to bottom
		scrollToBottom();

	}

	private void addBuddyMessageItem(ChatItem item) {
		int viewid = genID();
		RelativeLayout layout = new RelativeLayout(this);
		int padding = AndroidUtils.Screen.dp2pix(10f);
		layout.setPadding(padding, padding, padding, padding);

		ImageView headerView = new ImageView(this);

		headerView.setId(viewid);

		// get the user logo,if missed,used the default one...
		Uri uri = HeaderController.Cache.getFromCache(item.fromid);
		if (uri != null) {
			headerView.setImageURI(uri);
		} else {

		}

		// add header photo
		int headerWidth = AndroidUtils.Screen.dp2pix(72f);
		RelativeLayout.LayoutParams headerParams = new RelativeLayout.LayoutParams(
				headerWidth, headerWidth);
		headerParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
		layout.addView(headerView, headerParams);

		// add message item
		TextView msgView = new TextView(this);
		msgView.setTextColor(Color.BLACK);
		msgView.setBackgroundResource(R.drawable.chat_buddy_bg);
		msgView.setGravity(Gravity.CENTER);
		RelativeLayout.LayoutParams messageParams = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		messageParams.addRule(RelativeLayout.RIGHT_OF, viewid);
		messageParams.setMargins(0, 0, padding, 0);

		layout.addView(msgView, messageParams);
		msgView.setText(item.content);

		chatPanel.addView(layout, new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.FILL_PARENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT));
	}

	private void addBuddyMessageItems(List<ChatItem> items) {

		long time = 0;

		for (ChatItem item : items) {

			if (time != item.time) {
				this.addTimeLineSaperate(item.time);
			}

			addBuddyMessageItem(item);

		}
		// scroll to bottom
		scrollToBottom();

	}

	private void remoteSend() {

		final String contentStr = this.content.getText().toString();
		if (StringUtils.isBlank(contentStr)) {
			AndroidUtils.toastShort("请输入要发送的内容");
			return;
		}

		SendMessageRequest req = new SendMessageRequest();
		req.setContent(contentStr);
		req.setUserid(buddy.userid);

		Net.doSimpleHttpRemoter(req, new SendMessageResponse(),
				new AsynCallback<Response>() {

					@Override
					public void callback(Response r) {

						if (!r.isOk()) {
							AndroidUtils.toastShort("消息【" + contentStr
									+ "】发送失败。");
							return;
						}

					}
				});

		// first add the message item to panel
		long time = System.currentTimeMillis();

		addMyMessageItem(contentStr, time);

		// clear input message
		this.content.setText("");

		// store message offline...
		storeMyMsg(contentStr, time);

		AndroidUtils.Keyboard.hideKeyboard(this);

	}

	private void storeMyMsg(String content, long time) {

		ChatItem mymsg = new ChatItem();
		mymsg.mymsg = ChatItem.MY_MSG;
		mymsg.userid = YoufangContext.getUser().userid;
		mymsg.fromid = buddy.userid;
		mymsg.content = content;
		mymsg.time = time;
		try {
			mymsg.store();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private BroadcastReceiver messageReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle buddle = intent.getExtras();
			int userid = buddle.getInt("userid");
			if (buddy.userid == userid) {
				ArrayList<ChatItem> datalist = buddle
						.getParcelableArrayList("datalist");
				addBuddyMessageItems(datalist);

			}

		}
	};

	@Override
	protected void onResume() {
		super.onResume();

	}

	protected void onPause() {
		super.onPause();

	}

	@Override
	protected void onStop() {
		super.onStop();

	}

	@Override
	protected void onDestroy() {

		BuddyMessageService.unReg(this, buddy);
		unregisterReceiver(messageReceiver);
		super.onDestroy();
	}

}
